#include <fcntl.h>
#include <stdio.h>
#include <strings.h>
#include <sys/epoll.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>

#define FIFO_CLEAR 0x1
#define BUFFER_LEN 20

int main() {
  int fd;

  fd = open("/dev/globalfifo", O_RDONLY | O_NONBLOCK);
  if (fd != -1) {
    struct epoll_event ev_globalfifo;
    int err;
    int epfd;
    if (ioctl(fd, FIFO_CLEAR, 0) < 0) {
      printf("ioctl command failure\n");
    }
    epfd = epoll_create(1);
    if (epfd < 0) {
      perror("epoll_create()");
      return;
    }
    bzero(&ev_globalfifo, sizeof(struct epoll_event));
    ev_globalfifo.events = EPOLLIN | EPOLLPRI;
    // 设置感兴趣的事件为写入

    err = epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev_globalfifo);
    // 将对应的fd加入到事件监听中
    if (err < 0) {
      perror("epoll_ctl()");
      return;
    }
    err = epoll_wait(epfd, &ev_globalfifo, 1, 15000);
    // epoll阻塞等待事件的到来，设置倒计时15s，
    if (err < 0) {
      perror("epoll_wait()");
    } else if (err == 0) {
      printf("no data input in 15 seconds");
    } else {
      // 监听到了对fd的写数据
      printf("FIFO is not empty");
    }
    err = epoll_ctl(epfd, EPOLL_CTL_DEL, fd, &ev_globalfifo);
    if (err < 0) {
      perror("epoll_ctl()");
    }
  } else {
    printf("Device open failure\n");
  }
}
